package com.heqiang.spring.context.support;

import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.factory.config.BeanFactoryPostProcessor;
import com.heqiang.spring.beans.factory.config.BeanPostProcessor;
import com.heqiang.spring.beans.factory.config.ConfigurableBeanFactory;
import com.heqiang.spring.context.ApplicationEvent;
import com.heqiang.spring.context.ApplicationListener;
import com.heqiang.spring.context.ConfigurableApplicationContext;
import com.heqiang.spring.context.event.ApplicationEventMulticaster;
import com.heqiang.spring.context.event.ContextClosedEvent;
import com.heqiang.spring.context.event.ContextRefreshedEvent;
import com.heqiang.spring.context.event.SimpleApplicationEventMulticaster;
import com.heqiang.spring.core.io.loader.DefaultResourceLoader;
import com.heqiang.spring.beans.factory.ConfigurableListableBeanFactory;

import java.util.Collection;
import java.util.Map;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";

    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    public void refresh () throws BeansException {
        //1,创建beanFactory，并加载BeanDefinition
        refreshBeanFactory();

        //2,获取beanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        //3,添加ApplicationContextAwareProcessor，让继承自ApplicationContextAwareProcessor的bean对象都能感知所属的Application
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

        //4,在bean实例化前执行BeanFactoryPostProcessor
        invokeBeanFactoryProcessors(beanFactory);

        //5,BeanProcessor需要提前于其他bean对象前执行注册操作
        registerBeanPostProcessors(beanFactory);

        //6,初始化事件发布者
        initApplicationEventMulticaster();

        //7，注册事件监听器
        registerListeners();

        //8，提前实例化单例bean对象
        beanFactory.preInstantiateSingletons();

        //9,发布容器刷新完成事件
        finishRefresh();

    }

    protected abstract void refreshBeanFactory() throws BeansException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();


    private void invokeBeanFactoryProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanPostProcessorMap.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
     }


     private void registerBeanPostProcessors (ConfigurableListableBeanFactory beanFactory) {
         Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class);
         for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) {
             beanFactory.addBeanPostProcessor(beanPostProcessor);
         }
     }


     private void initApplicationEventMulticaster() {
         ConfigurableListableBeanFactory beanFactory = getBeanFactory();
         applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
         beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,applicationEventMulticaster);
     }


     private void registerListeners() {
         Collection<ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class).values();
         for (ApplicationListener applicationListener : applicationListeners) {
             applicationEventMulticaster.addApplicationListener(applicationListener);
         }
     }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return getBeanFactory().getBeansOfType(type);
    }


    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return getBeanFactory().getBean(name);
    }


    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return getBeanFactory().getBean(name,args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getBeanFactory().getBean(name,requiredType);
    }


    @Override
    public void registerShutdownHok() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    }

    @Override
    public void close() {
        //发布容器关闭事件
        publishEvent(new ContextClosedEvent(this));
        //执行销毁单例bean的销毁方法
        getBeanFactory().destroySingletons();
    }


    private void finishRefresh() {
        publishEvent(new ContextRefreshedEvent(this));
    }


    @Override
    public void publishEvent(ApplicationEvent event) {
        applicationEventMulticaster.multicastEvent(event);
    }
}
